﻿using System;
using System.Linq;
using System.Xml.Linq;
using System.Windows;
using System.ServiceModel;
using System.ServiceModel.Channels;
using PmuRegistry.Silverlight.PmuRegistryDataServiceProxy;
using System.Windows.Browser;

namespace PmuRegistry.Silverlight.Utilities
{
	public static class Common
	{
		public static Message ParseStringToMessage(string messageXML)
		{
			XDocument xdoc = XDocument.Parse(messageXML.Substring(1));
			var message = from element in xdoc.Descendants("Message")
						  select new Message()
						  {
							  UserMessageType = (MessageType)Enum.Parse(typeof(MessageType), element.Element("UserMessageType").Value, true),
							  UserMessage = element.Element("UserMessage").Value,
							  SystemMessage = element.Element("SystemMessage").Value
						  };
			return message.ToList()[0] as Message;
		}

		public static PhasorDataServiceClient GetPhasorDataServiceClient()
		{
			string baseServiceUrl = Application.Current.Resources["BaseServiceUrl"].ToString();
			EndpointAddress address = new EndpointAddress(baseServiceUrl + "Service/PhasorDataService.svc");
			CustomBinding binding;
            if (HtmlPage.Document.DocumentUri.Scheme.ToLower().StartsWith("https"))
            {
                HttpsTransportBindingElement httpsTransportBindingElement = new HttpsTransportBindingElement();
                httpsTransportBindingElement.MaxReceivedMessageSize = int.MaxValue;		// 65536 * 50;
                binding = new CustomBinding(
                                    new BinaryMessageEncodingBindingElement(),
                                    httpsTransportBindingElement
                                    );
            }
            else
            {
                HttpTransportBindingElement httpTransportBindingElement = new HttpTransportBindingElement();
                httpTransportBindingElement.MaxReceivedMessageSize = int.MaxValue;		// 65536 * 50;
                binding = new CustomBinding(
                                    new BinaryMessageEncodingBindingElement(),
                                    httpTransportBindingElement
                                    );
            }
            binding.CloseTimeout = new TimeSpan(0, 20, 0);
            binding.OpenTimeout = new TimeSpan(0, 20, 0);
            binding.ReceiveTimeout = new TimeSpan(0, 20, 0);
            binding.SendTimeout = new TimeSpan(0, 20, 0);
			return new PhasorDataServiceClient(binding, address);
		}

        public static void SetDefaultSystemSettings(bool overWrite)
        {
            //Check if system settings are available in the isolated storage. If not, then assign them default values.
            if (!IsolatedStorageManager.Contains("DefaultHeight") || overWrite)
                IsolatedStorageManager.SaveIntoIsolatedStorage("DefaultHeight", 750);

            if (!IsolatedStorageManager.Contains("DefaultWidth") || overWrite)
                IsolatedStorageManager.SaveIntoIsolatedStorage("DefaultWidth", 900);

            if (!IsolatedStorageManager.Contains("MinimumHeight") || overWrite)
                IsolatedStorageManager.SaveIntoIsolatedStorage("MinimumHeight", 600);

            if (!IsolatedStorageManager.Contains("MinimumWidth") || overWrite)
                IsolatedStorageManager.SaveIntoIsolatedStorage("MinimumWidth", 720);

            if (!IsolatedStorageManager.Contains("ResizeWithBrowser") || overWrite)
                IsolatedStorageManager.SaveIntoIsolatedStorage("ResizeWithBrowser", true);

            if (!IsolatedStorageManager.Contains("MaintainAspectRatio") || overWrite)
                IsolatedStorageManager.SaveIntoIsolatedStorage("MaintainAspectRatio", true);

            if (!IsolatedStorageManager.Contains("NumberOfMessagesOnMonitor") || overWrite)
                IsolatedStorageManager.SaveIntoIsolatedStorage("NumberOfMessagesOnMonitor", 75);
        }

        public static string CleanText(this string value)
        {
            return value.Trim().Replace("'", "").Replace("%", "");
        }

        public static bool IsInteger(this string value)
        {
            int temp;            
            return int.TryParse(value.CleanText(), out temp);
        }

        public static bool IsDecimal(this string value)
        {
            decimal temp;
            return decimal.TryParse(value.CleanText(), out temp);
        }

        public static bool IsDouble(this string value)
        {
            double temp;
            return double.TryParse(value.CleanText(), out temp);
        }

        public static int ToInteger(this string value)
        {
            int temp = 0;
            int.TryParse(value.CleanText(), out temp);
            return temp;
        }

        public static decimal ToDecimal(this string value)
        {
            decimal temp = 0;
            decimal.TryParse(value.CleanText(), out temp);
            return temp;
        }

        public static double ToDouble(this string value)
        {
            double temp = 0;
            double.TryParse(value.CleanText(), out temp);
            return temp;
        }

        public static int? ToNullableInteger(this string value)
        {
            int temp = 0;
            if (int.TryParse(value.CleanText(), out temp))
                return temp;
            else
                return (int?)null;
        }

        public static decimal? ToNullableDecimal(this string value)
        {
            decimal temp = 0;
            if (decimal.TryParse(value.CleanText(), out temp))
                return temp;
            else
                return (decimal?)null;
        }

        public static double? ToNullableDouble(this string value)
        {
            double temp = 0;
            if (double.TryParse(value.CleanText(), out temp))
                return temp;
            else
                return (double?)null;
        }

    }
}
